<template>
  <div class="sku pl20">
    <p class="f18 mb24">sku明细</p>

    <div class="specs-wrap">
      <div class="specs-item" v-for="(item, index) in specesList" :key="index">
        <el-form :inline="true" :model="item" class="demo-form-inline">
          <el-row>
            <!-- 一级规格 -->
            <el-col :span="24" class="level1-box mb10">
              <div>
                <el-form-item label="商品规格">
                  <el-select
                    class="level1"
                    v-model="item['specificationId']"
                    placeholder="请选择"
                    style="width: 240px"
                    @change="typeChange1(item)"
                  >
                    <el-option
                      v-for="(item, index) in typeOptions"
                      :key="index"
                      :label="item.specificationName"
                      :value="item.specificationId"
                      :disabled="selectedLevel1.includes(item.specificationId)"
                    />
                  </el-select>
                </el-form-item>
                <span>
                  <el-icon class="del-icon" @click="delLevel1(item, index)"><Delete /></el-icon>
                </span>
              </div>

              <div>
                <!-- 二级规格 -->
                <el-col :span="24" class="level2-box pt20">
                  <template v-if="item.levelType === 1">
                    <p v-for="(item2, index2) in item.children" :key="index2" style="display: inline-flex">
                      <el-form-item :label="item?.typeObj?.specificationName || '-'" label-width="80">
                        <div>
                          <el-select
                            v-model="item2['specificationValId']"
                            placeholder="请选择"
                            style="width: 240px"
                            @change="typeChange2(item, item2)"
                          >
                            <el-option
                              v-for="(_item2, _index2) in item?.typeObj?.children"
                              :key="_index2"
                              :label="_item2.specificationVal"
                              :value="_item2.specificationValId"
                              :disabled="selectedLevel2.includes(_item2.specificationValId)"
                            />
                          </el-select>

                          <!-- 上传图片 -->
                          <el-upload
                            v-show="item.speType === 3"
                            class="upload-card mt10"
                            list-type="picture-card"
                            :auto-upload="false"
                            :show-file-list="false"
                            :on-change="
                              (file, fileList) => {
                                handleAvatarChangeIcon(item2, file, fileList);
                              }
                            "
                          >
                            <img
                              v-if="item2['statsText'] && item2['statsText'].includes('51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/')"
                              :src="item2['statsText']"
                              style="width: 100%; height: 100%; object-fit: cover"
                            />
                            <p v-else class="f12">上传图片</p>
                          </el-upload>
                        </div>
                      </el-form-item>
                      <span class="ml8 mr16 mt10" style="display: inline-block">
                        <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                      </span>
                    </p>
                    <el-button
                      :disabled="item.children.length >= item?.typeObj?.children.length"
                      link
                      type="primary"
                      @click="addLevel2(item)"
                      >添加规格值</el-button
                    >
                  </template>
                  <template v-else>
                    <div v-for="(item2, index2) in item.children" :key="index2" style="display: inline-flex">
                      <!-- <div class="jsxcom-wrap"> -->
                      <!-- 规范数值输入 -->
                      <template v-if="item.levelType === 3">
                        <div class="jsxcom-wrap">
                          <jsxCom
                            :str="replaceNS(item['propTemplate'], -1)"
                            :viewValueStr="item2['specificationVal'] || ''"
                            @submit="
                              (strNS, inputArr) => {
                                const ARR = [];
                                strNS.map((obj, index) => {
                                  if (inputArr[index] !== undefined) {
                                    ARR.push(inputArr[index]);
                                  } else if (obj === 'N' || obj === 'S') {
                                    ARR.push('');
                                  }
                                });
                                item2['propTemplate'] = item.propTemplate;
                                item2['specificationValId'] = item.specificationId;
                                item2['specificationVal'] = ARR.join(',');
                                typeChange2(item, item2);
                                console.log('bbbbbbbbbbbbbbbb属性数据===', item);
                              }
                            "
                          />
                          <span class="ml8 mr16 mt10" style="display: inline-block">
                            <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                          </span>
                        </div>
                      </template>

                      <!-- 普通输入 -->
                      <template v-if="item.levelType === 2">
                        <div class="jsxcom-wrap">
                          <el-input
                            placeholder="请输入"
                            v-model="item2['specificationVal']"
                            @change="
                              val => {
                                console.log(111111, val);
                                item2['propTemplate'] = item.propTemplate;
                                item2['specificationValId'] = item.specificationId;
                                item2['specificationVal'] = val;
                                typeChange2(item, item2);
                              }
                            "
                          />
                          <span class="ml8 mr16 mt10" style="display: inline-block">
                            <el-icon class="del-icon" @click="delLevel2(item, index2)"><Delete /></el-icon>
                          </span>
                        </div>
                      </template>
                      <!-- </div> -->
                    </div>

                    <el-button link type="primary" @click="addLevel2(item)">添加规格值</el-button>
                  </template>
                </el-col>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-button class="mb40" link type="primary" @click="addLevel1">继续添加</el-button>
    </div>

    <!-- 单位 -->
    <el-form :model="unitForm" ref="unitFormRef" :rules="unitFormRules" label-width="auto" style="max-width: 600px">
      <el-form-item label="商品单位" prop="unit">
        <el-select v-model="unitForm.unit" placeholder="Select" style="width: 240px" @change="handCreateSku">
          <el-option v-for="(item, index) in units" :key="index" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
        <!-- <el-button type="primary" @click="handCreateSku">生成sku</el-button> -->
      </el-form-item>
    </el-form>

    <p class="f18 mb20 mt20">生成总览表单</p>
    <el-table border stripe :data="skuList" style="width: 100%" class="mb40 jzt-table" :span-method="spanMethod">
      <!-- :span-method="spanMethod" -->
      <el-table-column fixed type="index" width="50" />
      <el-table-column v-for="(item, index) in skuCols" :label="item.split('-')[0]" :key="index">
        <template #default="scope">
          <img
            v-if="item.split('-')[1] === '3' && getSkuImgUrl(item, scope.row)"
            :src="getSkuImgUrl(item, scope.row)"
            alt=""
            style="width: 80px; height: 80px; object-fit: cover; vertical-align: middle"
          />
          {{ scope.row[item.split("-")[0]] }}
        </template>
      </el-table-column>
      <el-table-column property="code" label="编码" width="100">
        <template #default="scope">
          <span>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column property="productUnit" label="单位" width="60">
        <template #default="scope">
          <span>{{ getUnitLabel(String(scope.row.productUnit)) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column property="factoryRealPrice" label="供应价" width="200">
        <template #default="scope">
          <el-input :disabled="scope.row.skuStatus === 0" v-model="scope.row.factoryRealPrice" type="number"></el-input>
        </template>
      </el-table-column> -->
      <el-table-column property="partNum" label="件数" width="110">
        <template #default="scope">
          <!-- <el-input v-model="scope.row.partNum" oninput="value=value.replace(/[^0-9]/g, '')"></el-input> -->
          <el-input-number
            class="jzt-input-number jzt-input-number-hidden"
            controls-position="right"
            v-model="scope.row.partNum"
            :min="0"
            style="width: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column property="factoryStock" label="库存" width="100">
        <template #default="scope">
          <el-input
            :disabled="scope.row.skuStatus === 0"
            v-model="scope.row.factoryStock"
            oninput="value=value.replace(/[^0-9]/g, '')"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column property="factoryPrice" label="正价" width="100">
        <template #default="scope">
          <el-input
            :disabled="
              scope.row.skuStatus === 0 ||
              !(scope.row.factoryPreferentialPrice === '' || scope.row.factoryPreferentialPrice === null)
            "
            v-model="scope.row.factoryPrice"
            oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column property="factoryPreferentialPrice" label="特价" width="100">
        <template #default="scope">
          <el-input
            :disabled="scope.row.skuStatus === 0 || !(scope.row.factoryPrice === '' || scope.row.factoryPrice === null)"
            v-model="scope.row.factoryPreferentialPrice"
            oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="是否设为SKU主推" width="140">
        <template #default="scope">
          <p v-if="!(scope.row.isMaster === 0 || scope.row.isMaster === 1)">没有这个字段-{{ scope.row.isMaste }}</p>
          <el-checkbox
            v-model="scope.row.isMaster"
            :disabled="scope.row.listingStatus === -1 || scope.row.skuStatus === 0"
            label="设为SKU主推"
            :true-value="1"
            :false-value="0"
            @change="changeAdminSKU($event, scope.row, skuList)"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="80" class-name="action-cell">
        <template #default="scope">
          <el-switch
            v-show="scope.row.skuStatus === 0"
            v-model="scope.row.skuStatus"
            active-text="重新启用"
            :active-value="1"
            :inactive-value="0"
          />
          <div v-show="scope.row.skuStatus === 1">
            <el-radio-group v-model="scope.row.listingStatus" @change="changeListing($event, scope.row)">
              <el-radio :label="1" :value="1">上架</el-radio>
              <el-radio :label="-1" :value="-1">下架</el-radio>
            </el-radio-group>
            <p><el-button type="danger" link @click="changeSkuStatus(scope.row, 0)">禁用</el-button></p>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-button @click="getSpecsOptios">test</el-button> -->
    <!-- <el-button type="primary" @click="getSkuList">获取sku列表数据/规格配置数据</el-button> -->
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { replaceNS } from "@/utils/index";
import { getSpecList } from "@/apis/products/specifications";
import { useRoute } from "vue-router";
const route = useRoute();
import jsxCom from "./jsxCom.vue";

const units = ref([]);
const unitForm = ref({});
const unitFormRules = ref({
  unit: [{ required: true, message: "请选择商品单位", trigger: "change" }]
});
const specesList = ref([{ children: [{}] }]); //动态 商品规格list
const typeOptions = ref([]); //level1 属性数据，包含level2数据
const skuList = ref([]);
const skuCols = ref(["表头名称"]);
const _optionInfo = ref({});

const props = defineProps({
  categoryId: {
    type: String,
    default: ""
  },
  Enums: {
    type: Array,
    default: () => []
  },
  optionInfo: {
    type: Object,
    default: () => {}
  }
});

watch(
  () => props.categoryId,
  val => {
    if (val) {
      //清空数据
      specesList.value = [{ children: [{}] }];
      typeOptions.value = [];
      skuList.value = [];
      skuCols.value = ["表头名称"]; // ["表头名称"] ['规格-1']

      //属性tree数据
      const productId = route.query.productId;
      if (!productId) {
        getSpecsOptios(); //获取规格配置下拉tree数据
      }
    }
  }
);
watch(
  () => props.Enums,
  val => {
    if (val) {
      //单位-shop_unit
      units.value = val.filter(item => {
        if (item.dictType === "shop_unit") {
          return item;
        }
      })[0].dictDataList;
      unitForm.value.unit = units.value[0].dictValue;
    }
  }
);
watch(
  () => props.optionInfo,
  async val => {
    if (val) {
      if (val.actionType === "edit" || val.actionType === "copy" || val.actionType === "re-applay") {
        _optionInfo.value = JSON.parse(JSON.stringify(val));
        console.log("sku的详情数据====", _optionInfo.value);
        await getSpecsOptios();

        specesList.value = JSON.parse(JSON.stringify(_optionInfo.value.editDetailInfo.specificationList));
        editReview(); //规格配置-编辑的时候sku table回显
        const { editDetailInfo } = _optionInfo.value;
        // console.log("sku table数据11111111111111111", editDetailInfo.skuList);

        apiTable.value = createSku(editDetailInfo.skuList, "init");
      }
    }
  },
  { deep: true }
);

onMounted(async () => {});

//更改上架、下架 radio
const changeListing = (val, row) => {
  // console.log("改变了", val);
  if (val === -1) {
    row.isMaster = 0;
  }
};

//更改“设为SKU主推”checked
const changeAdminSKU = (val, row, list) => {
  console.log("更改“设为SKU主推”checked====", val);
  list.map(item => {
    item.isMaster = 0;
  });
  row.isMaster = val;
};

//获取sku列表的图片规格的地址
const getSkuImgUrl = (item, row) => {
  const key = item.split("-")[0];
  const value = row[key];
  const properObj = row.properties.find(_item => _item.specificationName === key && _item.specificationVal === value);
  return properObj.statsText;
};

const apiTable = [];
const editSkuList = ref([]);
/**校验规格是否选择完整 */
const validateSpe = () => {
  /**规格没做任何选择 */
  console.log(11111111111, specesList.value);
  let flag = true; //规格是否都做了有效选择
  for (let item of specesList.value) {
    if (item.levelType !== 3) {
      for (let _item of item.children) {
        if (!item.specificationId || !_item.specificationValId) {
          flag = false;
        }
      }
    } else {
      for (let _item of item.children) {
        if (_item.specificationVal) {
          const arr = _item.specificationVal.split(","); //可能会包含空或者undefined
          const _arr = arr.filter(item => {
            if (item) {
              return item;
            }
          });
          const isWriteAll = arr.length === _arr.length;
          flag = isWriteAll;
        } else {
          flag = false;
        }
      }
    }
  }
  return flag;
};
const handCreateSku = obj => {
  if (obj && obj?.levelType === 3) {
  } else {
    if (!validateSpe()) {
      ElMessage({
        message: "请完善规格选择，并填写完整规范数值相关配置",
        type: "error"
      });
      return;
    }
  }
  const { actionType, editDetailInfo } = _optionInfo.value;
  if (JSON.stringify(_optionInfo.value) === "{}") {
    createSku();
  } else {
    const resSpe = editDetailInfo.specificationList; //接口返回的规格
    const pageSpe = specesList.value; //页面编辑后的规格
    console.log("接口返回的规格===", resSpe);
    console.log("页面编辑后的规格===", pageSpe);
    const resSpeIds = resSpe.map(item1 => item1.specificationId); //旧的一级规格ids
    const pageSpeIds = pageSpe.map(item2 => item2.specificationId); //新的一级规格ids
    let resSpeChildIds = []; //旧的二级规格ids
    let pageSpeChildIds = []; //新的二级规格ids
    resSpe.map(item3 => {
      item3.children.map(_item3 => {
        resSpeChildIds.push(_item3.specificationValId);
      });
    });
    pageSpe.map(item4 => {
      item4.children.map(_item4 => {
        pageSpeChildIds.push(_item4.specificationValId);
      });
    });

    const isChangeLevel1 = compareSpeLevel1(resSpeIds, pageSpeIds); //一级规格是否变动了，变动了就按照新增的逻辑处理
    // console.log("一级规格是否变动了===", isChangeLevel1);
    if (isChangeLevel1) {
      const oldTable = JSON.parse(JSON.stringify(apiTable.value));
      for (let item of oldTable) {
        item.delTag = 1;
      }
      console.log(111111111, oldTable);
      createSku(); //生成新的add newTable
      const newTable = JSON.parse(JSON.stringify(skuList.value));
      console.log(222222222, skuList.value);
      editSkuList.value = [...oldTable, ...newTable];
      console.log("一级删除后的数据===", editSkuList.value);
    } else {
      compareSpeLevel2(resSpeChildIds, pageSpeChildIds);
    }

    // compareSpeLevel1(resSpeIds, pageSpeIds);
    // compareSpeLevel2(resSpeChildIds, pageSpeChildIds);
  }
};

const compareSpeLevel1 = (resIds1, pageIds1) => {
  let flag = false; //一级规格是否变动
  const { added, removed } = compareArrays(resIds1, pageIds1);
  // console.log("add==", added);
  // console.log("removed==", removed);
  if (added.length > 0 || removed.length > 0) {
    console.log("一级规格做了更改，旧的数据全部删除，新生成的数据全部添加");
    flag = true;
  }
  return flag;
};

const compareSpeLevel2 = (resIds2, pageIds2) => {
  const { editDetailInfo } = JSON.parse(JSON.stringify(props.optionInfo));
  const InitTable = createSku(editDetailInfo.skuList); //每次重新生成sku时，重置table为接口返回的数据
  editSkuList.value = InitTable;

  let { added, removed } = compareArrays(resIds2, pageIds2);
  console.log("add==", added);
  console.log("removed==", removed);
  console.log("resIds2, pageIds2==", resIds2, pageIds2, resIds2 === pageIds2);

  const apiLevelType3Arr = typeOptions.value.filter(item => item.levelType === 2 || item.levelType === 3) || [];
  const apiLevelType3IdsArr = apiLevelType3Arr.map(item => item.specificationId);
  const pageLevelType3IdsArr = []; //y页面上规范数值规格的ids
  pageIds2.map(id => {
    if (apiLevelType3IdsArr.includes(id) && !added.includes(id)) {
      pageLevelType3IdsArr.push(id);
    }
  });
  added = [...added, ...pageLevelType3IdsArr];
  removed = [...removed, ...pageLevelType3IdsArr];
  console.log("修改了规范输入");

  if (removed.length > 0) {
    // 有删除的规格
    const table = skuList.value.map(item => {
      const ids = item.properties.map(_item => _item.specificationValId);
      //ids任意一个包含在removed中，就删除该数据
      for (let __item of ids) {
        if (removed.includes(__item)) {
          //删除
          item.delTag = 1;
        }
      }
      return item;
    });
    editSkuList.value = JSON.parse(JSON.stringify(table)); //把保留、删除的数据存在editSkuList中
    skuList.value = table.filter(item => item?.delTag !== 1 || !item?.delTag);
    console.log("删除后的table 只改变原来的delTag====", table);
  }
  if (added.length > 0) {
    // 有新增的规格

    let addTable = [];
    let cols = [];
    for (let addItem of added) {
      let _Arr = [];
      let index = 0;

      // console.log(1111111111111, specesList.value);
      for (let item of specesList.value) {
        const arr1 = [];
        const parentArr = []; //新增二级规格，它对应的一级规格id集合
        for (let _item of typeOptions.value) {
          const childIds = _item.children.map(__item => __item.specificationValId);
          if (childIds.includes(addItem)) {
            parentArr.push(_item.specificationId);
          }
        }
        if (!parentArr.includes(item.specificationId)) {
          console.log("新增规格2的父级不在这个对象===11111111", item);
          let { propTemplate, specificationName, specificationId, speType } = { ...item };
          const obj = { propTemplate, specificationName, specificationId, speType, sort: item.sort || index + 1 };
          for (let _item of item.children) {
            _item = Object.assign(_item, obj);
          }
          arr1.push(item.children);
        } else {
          console.log("新增规格2的父级在这个对象===222222222", item);
          const curr = item.children.filter(_item2 => _item2.specificationValId === addItem)[0];
          arr1.push([
            {
              ...curr,
              specificationId: item.specificationId,
              specificationName: item.specificationName,
              speType: item.speType,
              sort: item.sort || index + 1
            }
          ]);
        }
        _Arr.push(arr1[0]);
        index++;
      }
      console.log("准备sku排列组合====", _Arr);
      let TableArr = multiplyData(_Arr, "init"); //进行排列组合 获得二维数组
      // console.log("sku====", TableArr);

      //处理组合后的table数据
      let _TableArr = [];
      for (let item of TableArr) {
        let obj = {
          properties: [],
          productUnit: unitForm.value.unit,
          factoryRealPrice: "1000",
          factoryStock: "1000",
          factoryPrice: "",
          factoryPreferentialPrice: "",
          isMaster: 0,
          picUrl: "sku图片;如果规格设置表[shop_product_specification]的第一个规格是图片类型",
          listingStatus: 1, //-1下架 0未上架 1已上架
          skuStatus: 1 //1启用 0禁用
        };

        for (let _item of item) {
          if (JSON.stringify(_item) !== "{}") {
            obj.properties.push(_item);
          }
        }

        _TableArr.push(obj);
      }
      const { Arr: _skuList, Cols: _skuCols } = formatTableData(_TableArr);
      cols = _skuCols;
      addTable.push(..._skuList);
    }

    /**去重 */
    let vals = [];
    const _addTable = [];
    for (let item of addTable) {
      let valStr = "";
      for (let _item of cols) {
        valStr += item[_item.split("-")[0]];
      }
      if (!vals.includes(valStr)) {
        _addTable.push(item);
        vals.push(valStr);
      }
    }
    // console.log("去重后的数据11111111===", _addTable);
    // console.log(9999999999999, editSkuList.value, _skuList);
    editSkuList.value = [...editSkuList.value, ..._addTable];
    skuList.value = editSkuList.value.filter(item => item?.delTag !== 1 || !item?.delTag);
  }

  if (updImg.value.length > 0) {
    console.log("进行了图片修改=========", updImg.value);
    const updIds = updImg.value.map(item => item.specificationValId);
    for (let item of skuList.value) {
      console.log("修改图片===", item);
      for (let _item of item.properties) {
        if (updIds.includes(_item.specificationValId)) {
          const updObj = updImg.value.filter(item2 => item2.specificationValId === _item.specificationValId)[0];
          item.statsText = updObj.statsText;
          _item.statsText = updObj.statsText;
        }
      }
    }
  }

  const keyOne = skuCols.value[0]?.split("-")[0];
  const skuListSort = skuList.value.sort(
    //状态排序
    (a, b) => {
      if (a[keyOne] != b[keyOne]) {
        return String(a[keyOne]).localeCompare(String(b[keyOne]));
      }
    }
  );
  console.log("这是排完序后的数据===", skuListSort);

  console.log("编辑后的数据2222222====", editSkuList.value);

  editSkuList.value.map(item => (item.productUnit = unitForm.value.unit));
  skuList.value.map(item => (item.productUnit = unitForm.value.unit));
};

const compareArrays = (arr1, arr2) => {
  let added = arr2.filter(element => !arr1.includes(element));
  let removed = arr1.filter(element => !arr2.includes(element));
  return { added, removed };
};

const getUnitLabel = value => {
  const obj = units.value.filter(item => {
    if (item.dictValue === value) {
      return item;
    }
  })[0];
  return obj?.dictLabel || "-";
};

//获取规格配置下拉tree数据
const getSpecsOptios = async () => {
  await getSpecList({ categoryId: props.categoryId }).then(res => {
    if (res.code === 200) {
      typeOptions.value = res.data;
      typeOptions.value = formatOptions(typeOptions.value);
      console.log("规格查询成功===", res);
    }
  });
};
//处理规格配置数据的tree结构
const formatOptions = tree => {
  let Arr = [];
  for (let item of tree) {
    let obj = {
      specificationId: item.specificationId,
      specificationName: item.name,
      speType: item.speType,
      levelType: item.levelType,
      propTemplate: item.propTemplate,
      children: []
    };
    for (let _item of item.children) {
      let _obj = {
        specificationVal: _item.name,
        specificationValId: _item.specificationId
      };
      if (item.speType === 3) {
        //是图片类型，把图片地址添加进去
        _obj["img"] = _item.statsText;
      }
      obj.children.push(_obj);
    }
    Arr.push(obj);
  }
  return Arr;
};

const createSku = (resSkuList, init) => {
  const { actionType, editDetailInfo } = _optionInfo.value;
  // console.log("createSku skuList===", resSkuList);

  if (resSkuList) {
    for (let item of resSkuList) {
      item.properties = JSON.parse(item.properties);
    }
    const { Arr: _skuList, Cols: _skuCols } = formatTableData(resSkuList);
    console.log("动态表头 2222222===", _skuCols, _skuList);
    let skuListSort = _skuList;
    if (init) {
      const SkuList = JSON.parse(JSON.stringify(_skuList));
      const keyOne = _skuCols[0]?.split("-")[0];
      console.log("要排序的表头===", keyOne);
      skuListSort = SkuList.sort((a, b) => {
        if (a[keyOne] != b[keyOne]) {
          return String(a[keyOne]).localeCompare(String(b[keyOne]));
        }
      });
      console.log("排序后的table===", skuListSort);
    }

    skuList.value = skuListSort;
    skuCols.value = _skuCols;
    editSkuList.value = skuListSort;
    return skuListSort;
  } else {
    const List = specesList.value.map((item, index) => {
      let { propTemplate, specificationName, specificationId, speType } = { ...item };
      const obj = { propTemplate, specificationName, specificationId, speType, sort: item.sort || index + 1 };
      for (let _item of item.children) {
        _item = Object.assign(_item, obj);
      }
      return item.children;
    });
    console.log("准备排列组合的规格list===", List);
    let TableArr = multiplyData(List, "init"); //进行排列组合 获得二维数组
    console.log("sku====", TableArr);

    //处理组合后的table数据
    let _TableArr = [];
    for (let item of TableArr) {
      let obj = {
        properties: [],
        productUnit: unitForm.value.unit,
        factoryRealPrice: "1000",
        factoryStock: "1000",
        factoryPrice: "",
        factoryPreferentialPrice: "",
        isMaster: 0,
        picUrl: "sku图片;如果规格设置表[shop_product_specification]的第一个规格是图片类型",
        listingStatus: 1, //-1下架 0未上架 1已上架
        skuStatus: 1 //1启用 0禁用
      };

      for (let _item of item) {
        if (JSON.stringify(_item) !== "{}") {
          obj.properties.push(_item);
        }
      }

      _TableArr.push(obj);
    }
    const { Arr: _skuList, Cols: _skuCols } = formatTableData(_TableArr);
    // console.log("最总得到的sku table数据", _skuList);
    console.log("动态表头===", _skuCols);

    /**arr实现分组 */
    const key = _skuCols[0]?.split("-")[0];
    const grouped = _skuList.reduce((acc, item) => {
      if (!acc[item[key]]) {
        acc[item[key]] = [];
      }
      acc[item[key]].push(item);
      return acc;
    }, {});
    const sortArr = [];
    for (let key in grouped) {
      sortArr.push(...grouped[key]);
    }

    skuList.value = sortArr;
    skuCols.value = _skuCols;
  }
};

//处理成el-table能渲染的数据
const formatTableData = list => {
  const Arr = [];
  let Cols = [];
  console.log("处理成el-table能渲染的数据222", list.length);
  for (let item of list) {
    let obj = { ...item };
    Cols = [];
    for (let _item of item.properties) {
      if (_item.img || _item?.statsText) {
        obj.picUrl = _item?.img || _item?.statsText;
        obj.statsText = _item?.statsText;
      }
      // obj[_item.specificationId] = _item.specificationName; //暂时去掉 id:name {111:颜色} 的转换
      if (_item.propTemplate) {
        const viewValueArr = _item.specificationVal.split(",");
        const _string = _item.propTemplate?.replace(/%f/g, "N");
        const string = _string?.replace(/%s/g, "S");
        const arr = Array.from(string);
        let indexArr = []; // [4,7,8]  值的index下标
        let valArr = []; // [4:66,7:pp,8:mm]
        arr.map((item, index) => {
          if (item === "N" || item === "S") {
            indexArr.push(index);
          }
        });
        indexArr.map((iItem, index) => {
          valArr[iItem] = viewValueArr[index];
        });
        const _arr = [];
        arr.map((item, index) => {
          if (valArr[index]) {
            _arr[index] = valArr[index];
          } else {
            if (item === "N" || item === "S") {
              _arr[index] = "";
            } else {
              _arr[index] = item;
            }
          }
        });
        // console.log("sssssssssssssssssssssssssss", arr, valArr);
        obj[_item.specificationName] = _arr.join(""); //转换成 {颜色:红色} {尺寸：M} {种类:沙发}
      } else {
        obj[_item.specificationName] = _item.specificationVal; //转换成 {颜色:红色} {尺寸：M} {种类:沙发}
      }

      if (!Cols.includes(_item.specificationName + "-" + _item.speType)) {
        Cols.push(_item.specificationName + "-" + _item.speType);
        // Cols.push(_item.specificationName);
      }
    }
    Arr.push(obj);
  }
  console.log("table数据===", Arr);
  return { Arr, Cols };
};

const editReview = () => {
  unitForm.value.unit = String(_optionInfo.value.editDetailInfo.skuList[0]?.productUnit);

  specesList.value?.map((item, index) => {
    if (item.specificationId) {
      typeChange1(item, "review");
    }
    if (item.children.length > 0) {
      item.children?.map((_item, _index) => {
        if (index === specesList.value.length - 1 && _index === item.children.length - 1) {
          console.log("这里要触发handCreateSku");
          typeChange2(item, _item, true); //循环到最后一次的时候，第三个参数为true，生成skuList
        } else {
          typeChange2(item, _item, false); //编辑的时候，第三个参数为false，否则规格过多时会卡死
        }
      });
    }
  });
};

const selectedLevel1 = ref([]);
const selectedLevel2 = ref([]);
//商品规格更改level1
const typeChange1 = (obj, type = "change") => {
  // console.log("商品规格更改111111111111", obj);
  setSelected1(); //获取已经选择过的level1，控制后面的不允许再次选择
  if (type === "change") obj.children = [{}]; //level1变化之后，清空level2列表
  const children = typeOptions.value.filter(item => {
    if (item.specificationId === obj.specificationId) return item;
  });
  obj["typeObj"] = children[0];
  const curObj = children[0] ? JSON.parse(JSON.stringify(children[0])) : {};
  delete curObj.children;
  obj = Object.assign(obj, curObj);
};

//商品规格更改level2
const typeChange2 = (item, item2, isCreateSku = true) => {
  // console.log("商品规格更改22222222222", item, item2);
  setSelected2(); //获取已经选择过的level2，控制后面的不允许再次选择
  const children = item?.typeObj?.children || [];
  const curr = children.filter(obj => {
    if (obj.specificationValId === item2.specificationValId) return obj;
  });
  const curObj = curr[0] ? JSON.parse(JSON.stringify(curr[0])) : {};
  item2 = Object.assign(item2, curObj);

  if (isCreateSku) {
    if (item.levelType === 3) {
      handCreateSku(item); //自动更新sku
    } else {
      handCreateSku(); //自动更新sku
    }
  }
};

const setSelected1 = () => {
  selectedLevel1.value = [];
  selectedLevel2.value = [];
  for (let item of specesList.value) {
    selectedLevel1.value.push(item.specificationId);
  }
};
const setSelected2 = () => {
  selectedLevel2.value = [];
  for (let item of specesList.value) {
    for (let _item of item.children) {
      selectedLevel2.value.push(_item.specificationValId);
    }
  }
};

const addLevel1 = () => {
  specesList.value.push({ children: [{}] });
};
const addLevel2 = item => {
  item.children.push({});
};
const delLevel1 = (item, index) => {
  if (specesList.value.length <= 1) return ElMessage.error("至少保留一条数据");
  specesList.value.splice(index, 1);
  setSelected1();
  handCreateSku(); //自动更新sku
};
const delLevel2 = (item, index) => {
  if (item.children.length <= 1) return ElMessage.error("至少保留一条数据");
  item.children.splice(index, 1);
  setSelected2();
  handCreateSku(); //自动更新sku
};

// 计算多个sku数组排列组合
const multiplyData = (newArrData, type) => {
  if (newArrData.length <= 1 && type === "init") {
    if (newArrData[0].length > 1) {
      newArrData[1] = [{}];
    } else {
      return newArrData;
    }
  }
  let len = newArrData.length;
  if (len == 0) {
    return [];
  }
  // 当数组长度大于等于2时
  if (len >= 2) {
    // 第一个数组的长度
    let len1 = newArrData[0].length;
    // 第二个数组的长度
    let len2 = newArrData[1].length;
    //  申明一个新数组,做数据暂存
    let items = new Array();
    // 申明新数组的索引
    let index = 0;
    // 2层嵌套循环,将组合放到新数组中
    for (let i = 0; i < len1; i++) {
      for (let j = 0; j < len2; j++) {
        if (items.length < index + 1) {
          items.push([]);
        }
        if (newArrData[0][i] instanceof Array) {
          items[index] = items[index].concat(newArrData[0][i].concat(newArrData[1][j]));
        } else {
          items[index] = items[index].concat([newArrData[0][i], newArrData[1][j]]);
        }
        index++;
      }
    }
    // // 将新组合的数组并到原数组中
    let newArr = new Array(len - 1);
    for (let i = 2; i < newArrData.length; i++) {
      newArr[i - 1] = newArrData[i];
    }
    newArr[0] = items;
    // 执行回调
    return multiplyData(newArr);
  } else {
    return newArrData[0];
  }
};

const changeSkuStatus = row => {
  row.skuStatus = 0; //禁用
  row.isMaster = 0;
};
const spanMethod = ({
  row, // 行
  column, // 列
  rowIndex, // 行索引
  columnIndex // 列索引
}) => {
  if (columnIndex === 1) {
    return setTableRowCol(row, rowIndex, [skuCols.value[0]]);
  }
};

/**
 * 合并行
 * @param {*} row
 * @param {*} rowIndex
 * @param {*} keys
 */
const setTableRowCol = (row, rowIndex, keys) => {
  let firstIndex = 0,
    rowspan = 1,
    colspan = 1;
  // 找到需要合并的行的下标
  firstIndex = skuList.value.findIndex(item => {
    return filterSameKeys(item, row, keys);
  });
  if (rowIndex === firstIndex) {
    // 需要合并的行数
    rowspan = skuList.value.filter(item => {
      return filterSameKeys(item, row, keys);
    }).length;
    colspan = 1;
  } else {
    // 被合并的行需要设置成0
    rowspan = 0;
    colspan = 0;
  }
  return {
    rowspan,
    colspan
  };
};
// 根据keys数组所有字段去做合并
const filterSameKeys = (item, row, keys) => {
  const _item = JSON.parse(JSON.stringify(item));
  let flag = true;
  keys.forEach(key => {
    flag = flag && _item[key.split("-")[0]] === row[key.split("-")[0]];
  });
  return flag;
};

const formatTable = list => {
  const LIST = JSON.parse(JSON.stringify(list));
  let Arr = [];
  for (let item of LIST) {
    item.picUrl = item.statsText || item?.picUrl;
    delete item.statsText;
    for (let _item of skuCols.value) {
      delete item[_item.split("-")[0]];
    }
    for (let __item of item.properties) {
      delete __item.img;
      // delete __item.speType;
    }
    item.properties = JSON.stringify(item.properties);
    Arr.push(item);
  }
  return Arr;
};

const formatSpecs = list => {
  const LIST = JSON.parse(JSON.stringify(list));
  let Arr = [];
  for (let item of LIST) {
    delete item.typeObj;
    delete item.speType;
    for (let _item of item.children) {
      delete _item.img;
      delete _item.speType;
    }
    Arr.push(item);
  }
  return Arr;
};

//====================================文件上传========================================================================================

import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { getFolder } from "@/utils/index";
const handleAvatarChangeIcon = (item, file, fileList) => {
  //选中文件触发的change事件
  // console.log(file);
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
  if (!isPNG && !isJPG) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式!");
    return false;
  } else {
    item["statsText"] = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
    // console.log("这里调用图片上传接口");
    customUpload(item, { file }); //调用上传文件api接口
  }
};

/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const updImg = ref([]);
const customUpload = async (item, option) => {
  // 合并已上传和当前上传文件

  const objName = getFileName(option.file.name);
  ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("图片上传成功，地址为===", res.fileUrl);
      item["statsText"] = res.fileUrl.split("?")[0];
      console.log("图片上传的item=====", item);

      handCreateSku(); //自动更新sku

      if (JSON.stringify(_optionInfo.value) !== "{}") {
        // 如果图片发生改变，同步更改sku表格的图片
        changeSkuImg(item);

        const resSpe = _optionInfo.value.editDetailInfo.specificationList; //接口返回的规格
        let resSpeChildIds = []; //旧的二级规格ids
        resSpe.map(item3 => {
          item3.children.map(_item3 => {
            resSpeChildIds.push(_item3.specificationValId);
          });
        });
        if (resSpeChildIds.includes(item.specificationValId)) {
          // 上传图片的规格二级id包含在接口返回的数据中，表示在更改图片
          const isHave =
            updImg.value.filter(item2 => item2.specificationValId === item.specificationValId)?.length > 0 ? true : false;
          if (isHave) {
            // 更改图片的id已存在于updImg，更改对应id的url
            for (let _item2 of updImg.value) {
              if (_item2.specificationValId === item.specificationValId) {
                _item2.statsText = item.statsText;
              }
            }
          } else {
            // 更改图片的id不在updImg中，直接push一个新的对象
            updImg.value.push({
              specificationValId: item.specificationValId,
              statsText: item.statsText
            });
          }
        }
      }
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

const changeSkuImg = item => {
  for (let _item of skuList.value) {
    for (let __item of _item.properties) {
      if (__item.specificationValId === item.specificationValId) {
        _item.statsText = item.statsText;
        __item.statsText = item.statsText;
      }
    }
    console.log(_item, item.specificationValId);
  }
};

//获取规格配置数据、sku表格数据
const getSkuList = () => {
  return new Promise((resolve, reject) => {
    if (skuList.value.length > 0) {
      const EditTable = JSON.parse(JSON.stringify(editSkuList.value));
      if (JSON.stringify(_optionInfo.value) !== "{}") {
        for (let item of EditTable) {
          for (let item2 of skuList.value) {
            if (JSON.stringify(item2.properties) === JSON.stringify(item.properties)) {
              item.factoryPrice = item2.factoryPrice;
              item.factoryPreferentialPrice = item2.factoryPreferentialPrice;
              item.isMaster = item2.isMaster;
              item.listingStatus = item2.listingStatus;
              item.skuStatus = item2.skuStatus;
            }
          }
        }
      }
      /**校验规格项是否选择完整 */
      if (!validateSpe()) {
        ElMessage({
          message: "请完善规格选择，并填写完整规范数值相关配置",
          type: "error",
          offset: 60
        });
        return;
      }

      /**校验sku是否填入了正价、特价、上架/下架*/
      const flag = validateTable(JSON.stringify(_optionInfo.value) !== "{}" ? EditTable : skuList.value);
      if (!flag) {
        ElMessage({
          message: "请确认sku是否填入了正价、特价、上架/下架",
          type: "error",
          offset: 60
        });
        return;
      }
      /**校验是否设为SKU主推*/
      const mainSkuFlag = validateMainSkuFlag(JSON.stringify(_optionInfo.value) !== "{}" ? EditTable : skuList.value);
      if (!mainSkuFlag) {
        ElMessage({
          message: "请设置SKU主推",
          type: "error",
          offset: 60
        });
        return;
      }
      const _skuTable =
        JSON.stringify(_optionInfo.value) !== "{}"
          ? formatTable(EditTable)
          : formatTable(JSON.parse(JSON.stringify(skuList.value)));
      const _specesList = formatSpecs(JSON.parse(JSON.stringify(specesList.value)));

      console.log("sku列表数据", _skuTable);
      console.log("规格配置tree数据", _specesList);

      resolve({
        skuList: _skuTable,
        specesList: _specesList
      });
    } else {
      ElMessage({
        message: "请生成SKU列表",
        type: "error"
      });
    }
  });
};
const validateTable = list => {
  let flag = true;
  for (let item of list) {
    if (item.delTag !== 1 && item.listingStatus === 1 && item.skuStatus === 1) {
      if (
        !(item.factoryPrice || item.factoryPreferentialPrice) ||
        (String(item.listingStatus) && String(item.listingStatus) !== "1" && String(item.listingStatus) !== "-1")
      ) {
        flag = false;
      }
    }
  }

  return flag;
};
const validateMainSkuFlag = list => {
  let flag = false;
  for (let item of list) {
    if (item.delTag !== 1 && item.listingStatus === 1) {
      if (item.isMaster === 1) {
        flag = true;
      }
    }
  }

  return flag;
};
defineExpose({
  getSkuList
});
</script>

<style lang="scss" scoped>
:deep(.action-cell) {
  .el-switch {
    display: block;
    height: 42px;
    .el-switch__label.el-switch__label--right {
      margin-left: 0;
      span {
        font-size: 12px;
      }
    }
  }
}
.jsxcom-wrap {
  border: 1px solid #dcdfe6;
  margin: 0 20px 10px 0;
  padding: 10px;
  display: flex;
}
:deep(.level1 .el-select__wrapper.el-tooltip__trigger.el-tooltip__trigger) {
  background-color: white;
}
p {
  margin: 0;
}
.level1-box {
  border: 1px solid #dcdfe6;
  padding: 24px 18px;
  & > div:first-of-type {
    background-color: #f5f7fa;
    padding: 9px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-form-item {
    margin-bottom: 0;
    margin-right: 0 !important;
  }
  .level2-box {
    .el-form-item {
      margin-bottom: 10px;
    }
    :deep(.el-form-item__label) {
      overflow-y: auto;
    }
  }
}
</style>
